package tcpchat02;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 用于数据发送 线程
 */
public class Send implements Runnable{
    //控制台输入流
    private BufferedReader br;
    //管道输出流
    private DataOutputStream dos;
    //控制线程
    private boolean isRunning=true;
    public Send() {
        InputStreamReader isr=new InputStreamReader(System.in);
        this.br = new BufferedReader(isr);
    }
    public Send(Socket client){
        this();
        try {
            this.dos=new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            isRunning=false;
            CloseUtil.closeAll(dos,br);
        }
    }

    /**
     * 1.从控制台接收数据
     * 2.发送数据
     */
    public String getMsgFromBr(){
        try {
            return br.readLine();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return "";
    }
    public void send(){
        String msg=getMsgFromBr();
        if (msg!=null&&!msg.equals("")){
            try {
                dos.writeUTF(msg);
                dos.flush();//强制刷新
            } catch (IOException e) {
                isRunning=false;
                CloseUtil.closeAll(dos,br);
            }
        }
    }
    @Override
    public void run() {
        //线程体
        while (isRunning){
            send();
        }
    }
}
